package com.wcpdoc.base.dao.impl;

import java.util.List;
import java.util.Map;

import org.hibernate.query.NativeQuery;
import org.hibernate.query.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import com.wcpdoc.base.dao.UserDao;
import com.wcpdoc.base.entity.User;
import com.wcpdoc.core.dao.impl.RBaseDaoImpl;
import com.wcpdoc.core.entity.PageIn;
import com.wcpdoc.core.entity.PageOut;
import com.wcpdoc.core.util.DateUtil;
import com.wcpdoc.core.util.HibernateUtil;
import com.wcpdoc.core.util.SqlUtil;
import com.wcpdoc.core.util.SqlUtil.Order;
import com.wcpdoc.core.util.ValidateUtil;

/**
 * 用户数据访问层实现
 * <p>
 * v1.0 zhanghc 2016-6-15下午17:24:19
 */
@Repository
public class UserDaoImpl extends RBaseDaoImpl<User> implements UserDao {
    private static final Logger log = LoggerFactory.getLogger(UserDaoImpl.class);

    @Override
    public PageOut getListpage(PageIn pageIn) {
        String sql = "SELECT USER.ID, USER.NAME, USER.PHONE, USER.EMAIL, USER.LOGIN_NAME, USER.ORG_ID, ORG.NAME AS ORG_NAME,USER.LABEL_ID,LABEL.NAME AS LABEL_NAME, "
                + "USER.STATE,case when USER.SEX ='1' then '男' when USER.SEX ='2' then '女' else '未知' end as SEX  "
                + "FROM SYS_USER USER "
                + "LEFT JOIN SYS_ORG ORG ON USER.ORG_ID = ORG.ID "
                + "LEFT JOIN SYS_LABEL LABEL ON USER.LABEL_ID = LABEL.ID ";

        SqlUtil sqlUtil = new SqlUtil(sql);
        sqlUtil.addWhere(ValidateUtil.isValid(pageIn.get("name")), "(USER.NAME LIKE :NAME OR ORG.NAME LIKE :ORG_NAME)", String.format("%%%s%%", pageIn.get("name")), String.format("%%%s%%", pageIn.get("name")))
                .addWhere(ValidateUtil.isValid(pageIn.get("state")), "USER.STATE = :USER_STATE", pageIn.get("state"))
                .addWhere(ValidateUtil.isValid(pageIn.get("type")), "USER.TYPE = :USER_TYPE", pageIn.get("type"))
                //            需求:设置子管理员和超管一样权限 2024-3-17
// 				.addWhere("USER.TYPE in (0,2)")
                .addWhere("USER.LOGIN_NAME != 'admin'")
                /* 2023/12/28 add : 用户标签 */
                .addWhere(ValidateUtil.isValid(pageIn.get("label_id")), "USER.LABEL_ID = :USER_LABEL_ID", pageIn.get("label_id"))
                /**/
                .addWhere(ValidateUtil.isValid(pageIn.get("ids")), "USER.ID IN (" + pageIn.get("ids") + ")")
				//            需求:设置子管理员和超管一样权限 2024-3-17
                // .addWhere(ValidateUtil.isValid(pageIn.get("parentId", Integer.class)), "USER.PARENT_ID = :PARENT_ID", pageIn.get("parentId", Integer.class))
                .addWhere("USER.STATE = 1 OR USER.STATE = 2")
                .addOrder("USER.UPDATE_TIME", Order.DESC);
        System.out.println("=======UserDaoImpl 日志打印");
        log.info("=======UserDaoImpl 日志打印");
        log.info(sqlUtil.toString());

        PageOut pageOut = getListpage(sqlUtil, pageIn);

        HibernateUtil.formatDate(pageOut.getList(), "registTime", DateUtil.FORMAT_DATE_TIME, "lastLoginTime", DateUtil.FORMAT_DATE_TIME);
        return pageOut;
    }

    @Override
    public List<Map<String, Object>> getListUser(String id) {
        String sql = "SELECT USER.ID, USER.NAME,USER.PHONE, USER.EMAIL,USER.LOGIN_NAME,ORG.NAME AS ORG_NAME,USER.LABEL_ID,LABEL.NAME AS LABEL_NAME, "
                + "case when USER.STATE =0 then '删除'  when USER.STATE =1 then '正常' when USER.STATE =2 then '冻结' else '未知' end as STATE," +
                " case when USER.sex ='1' then '男'  when USER.sex ='2' then '女' else '未知' end as sex "
                + "FROM SYS_USER USER "
                + "LEFT JOIN SYS_ORG ORG ON USER.ORG_ID = ORG.ID "
                + "LEFT JOIN SYS_LABEL LABEL ON USER.LABEL_ID = LABEL.ID " +
                " where 1=1 and USER.PARENT_ID = '" + id + "' and USER.STATE = 1 OR USER.STATE = 2 and USER.type = 1 ";
        return getMapList(sql);
    }

    @Override
    public User getUser(String loginName) {
        String sql = "SELECT * FROM SYS_USER WHERE LOGIN_NAME = :LOGIN_NAME AND STATE != 0";
        return getEntity(sql, new Object[]{loginName});
    }

    @Override
    public boolean existLoginName(String loginName, Integer excludeId) {
        if (excludeId == null) {
            String sql = "SELECT COUNT(*) AS NUM FROM SYS_USER WHERE LOGIN_NAME = :LOGIN_NAME AND STATE != 0";
            return getCount(sql, new Object[]{loginName}) > 0;
        }

        String sql = "SELECT COUNT(*) AS NUM FROM SYS_USER WHERE LOGIN_NAME = :LOGIN_NAME AND STATE != 0 AND ID != :ID";
        return getCount(sql, new Object[]{loginName, excludeId}) > 0;
    }

    @Override
    public List<User> getList(Integer orgId) {
        String sql = "SELECT * FROM SYS_USER WHERE ORG_ID = :ORG_ID AND STATE != 0";
        return getList(sql, new Object[]{orgId});
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<User> getList(Integer[] ids) {
        String sql = "SELECT * FROM SYS_USER WHERE ID IN (:IDS) AND STATE != 0";
        Query<User> query = getCurSession().createSQLQuery(sql);
        query.setParameterList("IDS", ids);
        query.unwrap(NativeQuery.class).addEntity(clazz);
        return query.list();
    }

    @Override
    public List<User> getList() {
        String sql = "SELECT * FROM SYS_USER WHERE STATE != 0";
        return getList(sql);
    }

    @Override
    public List<User> getMarkUserlist(Integer parentId) {
        String sql = "SELECT * FROM SYS_USER WHERE TYPE = 3 AND STATE != 0 AND PARENT_ID = :PARENT_ID";
        return getList(sql, new Object[]{parentId});
    }
}
